// index.js
const app = getApp()
const data = require('../../config/data.js');
const packData = require('../../config/pack-data.js')

Page({
  data: {
    currentDish: null,
    loading: true,
    error: null,
    switchCount: 0,
    showCookEffect: false,
    isChanging: false,
    cardAnimationClass: '',
    likedDishId: null,
    // 收藏相关
    favoriteList: [],
    showFavoriteMode: false,
    // 预设相关
    showPresetPanel: false,
    packList: [],
    selectedPackId: null,
    // 筛选相关
    categories: [],
    tags: [],
    // 菜品数据
    allDishes: [],
    filteredDishes: [],
    // 查看更多相关
    showMorePanel: false,
    displayDishes: [],
    currentPackName: '全部',
    dislikeList: [],
    filterText: "全部"
  },

  onLoad() {
    wx.setEnableDebug({
      enableDebug: false
    });
    // 检查本地存储中是否有喜欢的菜品，并检查是否需要重置
    this.checkAndResetLikedDish();
    // 加载收藏列表
    this.loadFavoriteList();
    // 加载菜品包数据
    this.loadPackData();
    this.loadDishData();
    this.initMeteorAnimation();
  },

  // 检查并重置喜欢的菜品（每日凌晨重置）
  checkAndResetLikedDish() {
    const lastResetDate = wx.getStorageSync('lastResetDate');
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();

    // 如果没有上次重置日期，或者上次重置日期不是今天，则重置
    if (!lastResetDate || parseInt(lastResetDate) < today) {
      console.log('重置喜欢的菜品记录');
      wx.removeStorageSync('likedDishId');
      wx.removeStorageSync('dislikeList');
      wx.setStorageSync('lastResetDate', today.toString());
      this.setData({
        likedDishId: null,
        dislikeList: []
      });
    } else {
      // 如果今天已经重置过，则读取喜欢的菜品
      const likedDishId = wx.getStorageSync('likedDishId');
      const dislikeList = wx.getStorageSync('dislikeList') || [];
      if (likedDishId) {
        this.setData({
          likedDishId: likedDishId
        });
      }
      this.setData({
        dislikeList: dislikeList
      });

    }
  },

  // 加载收藏列表
  loadFavoriteList() {
    const favoriteList = wx.getStorageSync('favoriteList') || [];
    this.setData({
      favoriteList: favoriteList
    });
  },

  // 加载菜品包数据
  loadPackData() {
    this.setData({
      packList: packData.packs || []
    });
  },

  // 加载本地菜品数据
  loadDishData() {
    let defaultDishes = [];
    try {
      // 从配置文件读取菜品数据

      // 在微信小程序中，直接使用require引入本地JS模块
      const fileContent = require('../../config/data.js');
      const data = fileContent;
      defaultDishes = data.dishes || [];
      console.log('成功读取菜品数据，共', defaultDishes.length, '条');


      // 提取所有分类和标签并去重
      const categoriesSet = new Set();
      const tagsSet = new Set();

      defaultDishes.forEach(dish => {
        if (dish.category) {
          categoriesSet.add(dish.category);
        }
        if (dish.tags && Array.isArray(dish.tags)) {
          dish.tags.forEach(tag => tagsSet.add(tag));
        }
      });

      // 检查是否有喜欢的菜品
      const likedDishId = this.data.likedDishId;
      if (likedDishId) {
        // 查找喜欢的菜品
        const likedDish = defaultDishes.find(dish => dish.id === likedDishId);
        if (likedDish) {
          // 如果找到喜欢的菜品，则显示它
          this.setData({
            currentDish: likedDish,
            loading: false,
            allDishes: defaultDishes,
            filteredDishes: defaultDishes,
            categories: Array.from(categoriesSet),
            tags: Array.from(tagsSet),
            displayDishes: defaultDishes,
            isFavorite: this.data.favoriteList.includes(likedDish.id)
          });
          return;
        }
      }

      // 如果没有喜欢的菜品或未找到，则随机显示一个
      this.setData({
        allDishes: defaultDishes,
        filteredDishes: defaultDishes,
        categories: Array.from(categoriesSet),
        tags: Array.from(tagsSet),
        displayDishes: defaultDishes,
        loading: false
      });
      this.getRandomDish();
    } catch (fileError) {
      console.error('无法读取data.js文件，使用默认数据:', fileError);
      // 如果读取文件失败，使用默认数据
      defaultDishes = [
        {
          id: 1,
          name: '红烧肉',
          category: '热菜',
          tags: ['招牌菜', '传统', '下饭'],
          calories: 450
        },
        {
          id: 2,
          name: '清蒸鲈鱼',
          category: '海鲜',
          tags: ['清淡', '营养', '鲜美'],
          calories: 180
        },
        {
          id: 3,
          name: '麻婆豆腐',
          category: '热菜',
          tags: ['川菜', '麻辣', '经典'],
          calories: 220
        },
        {
          id: 4,
          name: '蒜蓉西兰花',
          category: '素菜',
          tags: ['清爽', '健康', '维生素'],
          calories: 80
        }
      ];

      // 提取所有分类和标签并去重
      const categoriesSet = new Set();
      const tagsSet = new Set();

      defaultDishes.forEach(dish => {
        if (dish.category) {
          categoriesSet.add(dish.category);
        }
        if (dish.tags && Array.isArray(dish.tags)) {
          dish.tags.forEach(tag => tagsSet.add(tag));
        }
      });

      this.setData({
        allDishes: defaultDishes,
        filteredDishes: defaultDishes,
        categories: Array.from(categoriesSet),
        tags: Array.from(tagsSet),
        loading: false
      });

      // 随机显示一个菜品
      this.getRandomDish();
      this.setData({
        loading: false
      });
      console.info('加载菜品数据成功' + this.data.loading);
    }

    // 移除了多余的catch块
  },

  // 获取随机菜品
  getRandomDish() {
    const {
      allDishes,
      favoriteList,
      showFavoriteMode,
      selectedPackId,
      packList,
      dislikeList
    } = this.data;

    let availableDishes = allDishes;

    // 如果是收藏模式，只从收藏列表中选择
    if (showFavoriteMode) {
      const favoriteDishes = allDishes.filter(dish =>
        favoriteList.includes(dish.id)
      );
      if (favoriteDishes.length === 0) {

        return;
      }
      availableDishes = favoriteDishes;
    }
    // 如果选择了菜品包，只从菜品包中选择
    else if (selectedPackId) {
      console.log('Filtering by pack ID:', selectedPackId, 'Pack list:', packList);
      const selectedPack = packList.find(pack => pack.id == selectedPackId); // 使用 == 而不是 === 来处理类型转换
      console.log('Found pack:', selectedPack);
      if (selectedPack && selectedPack.dishIds) {
        const packDishes = allDishes.filter(dish =>
          selectedPack.dishIds.includes(dish.id)
        );
        console.log('Pack dishes found:', packDishes.length, packDishes.map(d => d.name));
        if (packDishes.length === 0) {
          this.setData({
            error: '菜品包中暂无可用菜品',
            currentDish: null
          });
          return;
        }
        availableDishes = packDishes;
      } else {
        console.error('Pack not found or no dishIds:', selectedPack);
      }
    }
    // 否则使用筛选条件
    else {
      // 按分类筛选
    }

    if (dislikeList && dislikeList.length > 0) {
      let first = availableDishes[0];
      availableDishes = availableDishes.filter(dish => !dislikeList.includes(dish.id));
      if (availableDishes.length == 0) {
        wx.showModal({
          title: '暂无更多',
          showCancel: true,
          cancelText: "立即重置",
          content: "已排除不喜欢选项（0点重置）",
          complete: (res) => {
            if (res.cancel) {
              wx.removeStorageSync('dislikeList');
              this.setData({
                dislikeList: []
              });
            }
          }
        });
        availableDishes.push(first);
      }
    }


    const randomIndex = Math.floor(Math.random() * availableDishes.length);
    const randomDish = availableDishes[randomIndex];

    if (favoriteList.includes(randomDish.id)) {
      console.log('Favorite dish:', randomDish);
      wx.setStorageSync('likedDishId', randomDish.id);
    } else {
      wx.removeStorageSync('likedDishId');
    }


    console.log('Random dish:', randomDish);
    console.log('Favorite list:', favoriteList);
    console.log("favorite contais: ", favoriteList.includes(randomDish.id))

    this.setData({
      favoriteList: favoriteList,
      currentDish: randomDish,
      error: null,
      loading: false,
      isFavorite: favoriteList.includes(randomDish.id),
      filteredDishes: availableDishes  // 更新筛选结果
    });
  },

  // 切换卡片
  switchCard() {
    if (this.data.loading || this.data.isChanging) return;

    this.setData({
      isChanging: true,
      loading: true
    });

    // 直接执行切换逻辑
    this.doSwitchCard();
  },



  // 初始化流星动画
  initMeteorAnimation() {
    this.createMeteor();
  },

  // 创建流星
  createMeteor() {
    const meteors = wx.createSelectorQuery();
    meteors.select('.starry-background').boundingClientRect((rect) => {
      if (rect) {
        // 随机创建流星
        const meteorInterval = setInterval(() => {
          this.addMeteorElement();
        }, Math.random() * 1500 + 1500); // 15-30秒随机间隔

        // 保存定时器引用以便清理
        this.meteorInterval = meteorInterval;
      }
    }).exec();
  },

  // 添加流星元素
  addMeteorElement() {
    // 由于微信小程序限制，这里使用CSS动画实现
    // 实际的流星动画通过CSS keyframes实现
    console.log('创建流星动画' + this.data.loading);
  },

  // 处理不喜欢按钮
  handleDislike() {
    // 清除喜欢的菜品记录
    wx.removeStorageSync('likedDishId');
    this.setData({ likedDishId: null });

    // 加入不喜欢列表
    let dislikeList = wx.getStorageSync('dislikeList') || [];
    dislikeList.push(this.data.currentDish.id);
    wx.setStorageSync('dislikeList', dislikeList);
    this.setData({
      dislikeList: dislikeList
    });


    // 切换到新菜品
    this.switchCard();
  },

  // 喜欢按钮点击事件
  handleLike() {
    if (this.data.isChanging || this.data.likedDishId === this.data.currentDish.id) return;

    const dishId = this.data.currentDish.id;

    // 保存喜欢的菜品到本地存储（每日重置）
    wx.setStorageSync('likedDishId', dishId);

    // 添加到收藏列表（永久保存）
    let favoriteList = wx.getStorageSync('favoriteList') || [];
    if (!favoriteList.includes(dishId)) {
      favoriteList.push(dishId);
      wx.setStorageSync('favoriteList', favoriteList);
    }

    // 更新状态
    this.setData({
      likedDishId: dishId,
      favoriteList: favoriteList,
      isFavorite: true

    });

    // 显示提示
    wx.showToast({
      title: '已收藏菜品',
      icon: 'success',
      duration: 1500
    });
  },

  // 执行切换动画
  doSwitchCard() {
    console.log('doSwitchCard called', this.data.loading);

    // 添加淡出动画
    this.setData({
      cardAnimationClass: 'card-fade-out'
    });

    // 等待淡出动画完成后切换菜品
    setTimeout(() => {
      this.getRandomDish();
      // 添加淡入动画
      this.setData({
        cardAnimationClass: 'card-fade-in'
      });

      // 动画完成后重置状态
      setTimeout(() => {
        this.setData({
          loading: false,
          isChanging: false,
          cardAnimationClass: ''
        });
      }, 300);
    }, 300);
  },

  // 处理更多按钮点击
  handleMoreClick() {
    console.log('handleMoreClick called', this.data.loading);
    // 如果是打开面板，根据当前选择的菜包展示菜品
    if (!this.data.showMorePanel) {
      this.updateMorePanelContent();
    }
    this.setData({
      showMorePanel: !this.data.showMorePanel,
      showPresetPanel: false
    });
  },

  // 隐藏查看更多面板
  hideMorePanel() {
    this.setData({ showMorePanel: false });
  },

  // 更新查看更多面板内容
  updateMorePanelContent() {
    const { selectedPackId, allDishes, favoriteList, packList } = this.data;
    let displayDishes = [];
    let currentPackName = '全部';

    if (selectedPackId === 'favorites') {
      // 显示收藏的菜品
      displayDishes = allDishes.filter(dish => favoriteList.includes(dish.id));
      currentPackName = '我的收藏';
    } else if (selectedPackId) {
      // 显示选中菜品包的菜品
      const selectedPack = packList.find(pack => pack.id === selectedPackId);
      if (selectedPack) {
        displayDishes = allDishes.filter(dish => selectedPack.dishIds.includes(dish.id));
        currentPackName = selectedPack.name;
      } else {
        displayDishes = allDishes;
      }
    } else {
      // 显示全部菜品
      displayDishes = allDishes;
      currentPackName = '全部';
    }

    this.setData({
      displayDishes,
      currentPackName
    });
  },



  // 删除收藏菜品
  removeFavorite(e) {
    const dishId = e.currentTarget.dataset.dishId;
    let favoriteList = this.data.favoriteList.filter(id => id !== dishId);

    // 更新本地存储
    wx.setStorageSync('favoriteList', favoriteList);

    // 更新状态
    this.setData({
      favoriteList: favoriteList
    });

    // 如果当前是收藏模式，更新显示列表
    if (this.data.showFavoriteMode) {
      this.filterFavoriteDishes();
    }

    wx.showToast({
      title: '已取消收藏',
      icon: 'success',
      duration: 1000
    });
  },

  // 从查看更多面板删除收藏菜品
  removeFavoriteFromMore(e) {
    console.log('removeFavoriteFromMore called', e);
    console.log('dataset:', e.currentTarget.dataset);

    const dishId = e.currentTarget.dataset.dishId;
    console.log('dishId before conversion:', dishId, typeof dishId);

    const numericDishId = parseInt(dishId);
    console.log('dishId after conversion:', numericDishId, typeof numericDishId);
    console.log('current favoriteList:', this.data.favoriteList);

    let favoriteList = this.data.favoriteList.filter(id => {
      console.log('comparing:', id, 'with', numericDishId, 'equal?', id === numericDishId);
      return id !== numericDishId;
    });

    console.log('new favoriteList:', favoriteList);

    // 更新本地存储
    wx.setStorageSync('favoriteList', favoriteList);

    // 更新状态
    this.setData({
      favoriteList: favoriteList
    });

    // 更新查看更多面板内容
    this.updateMorePanelContent();

    wx.showToast({
      title: '已取消收藏',
      icon: 'success',
      duration: 1000
    });
  },

  // 预设按钮点击
  handlePresetClick() {
    this.setData({
      showPresetPanel: !this.data.showPresetPanel,
      showMorePanel: false
    });
  },

  // 隐藏预设面板
  hidePresetPanel() {
    this.setData({ showPresetPanel: false });
  },

  // 选择菜品包
  selectPack(e) {
    const packId = e.currentTarget.dataset.packId;
    console.log('Selected pack ID:', packId);

    if (!packId) {
      console.error('Pack ID is undefined');
      return;
    }

    this.setData({
      selectedPackId: packId,
      showFavoriteMode: false,  // 选择菜品包时退出收藏模式
      showPresetPanel: false,
      filterText: this.data.packList.find(pack => pack.id === packId).name

    });

    // 立即随机一道菜
    this.getRandomDish();
  },

  // 选择我的收藏菜品包
  selectFavoritesPack(e) {
    const { favoriteList, allDishes } = this.data;

    if (favoriteList.length === 0) {
      wx.showToast({
        title: '暂无收藏菜品',
        icon: 'none'
      });
      return;
    }
    console.log('Favorite list:', favoriteList);

    // 从收藏的菜品ID中找到对应的菜品对象
    const favoriteDishes = allDishes.filter(dish => favoriteList.includes(dish.id));
    if (favoriteDishes.length === 0) {
      wx.showToast({
        title: '收藏的菜品不存在',
        icon: 'none'
      });
      return;
    }

    // 从收藏菜品中随机选择一道
    this.setData({
      selectedPackId: 'favorites',
      cardAnimationClass: 'fade-in',
      showFavoriteMode: true,
      filterText: "我的收藏"

    });

    this.getRandomDish();

    // 隐藏预设面板
    this.hidePresetPanel();

    // 重置动画类
    setTimeout(() => {
      this.setData({
        cardAnimationClass: ''
      });
    }, 300);
  },

  // 清除菜品包选择
  clearPackSelection() {
    this.setData({
      selectedPackId: null,
      showFavoriteMode: false

    });

    wx.showToast({
      title: '已清除菜品包选择',
      icon: 'success',
      duration: 1000
    });
  },


  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  onUnload() {
    // 清理定时器
    if (this.meteorInterval) {
      clearInterval(this.meteorInterval);
    }
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '今天吃什么',
      path: '/pages/index/index',
      imageUrl: '' // 可以设置分享图片
    }
  }
})